<template>
  <div
    class="blackboard-item"
    :style="noteStyle"
    :class="type"
    @click="$emit('on-click',id)"
  >
    <div class="drag" @mousedown="onDragStart"></div>
    <div class="size" @mousedown="onResizeStart"></div>
    <div v-html="content" contenteditable="true"
    @input="onInput"></div>
  </div>
</template>
<script>
import Style from '../../utils/styleBuilder'
export default {
  name: 'blackboard-item',
  props: {
    id: {
      type: Number,
      required: true,
    },
    type: {
      type: String,
      required: true,
      validator: data => {
        return ['text'].indexOf(data) >= 0
      },
    },
    positionX: {
      type: Number,
      required: true,
    },
    positionY: {
      type: Number,
      required: true,
    },
    width: {
      type: Number,
      required: true,
    },
    color: {
      type: String,
      required: true,
    },
    fontSize: {
      type: Number,
      default: 26,
    },
    content: {
      type: String,
      required: true,
    },
  },
  computed: {
    noteStyle () {
      var style = new Style()
      style.add('color:' + this.color)
      style.add('width:' + this.width + 'px')
      style.add('left:' + this.positionX + 'px')
      style.add('top:' + this.positionY + 'px')
      style.add('font-size:' + this.fontSize + 'px')
      return style.result()
    },
  },
  data () {
    return {
      timmer: null,
    }
  },
  methods: {
    onInput (e) {
      window.clearTimeout(this.timmer)
      this.timmer = window.setTimeout(() => {
        this.$emit('on-save', { id: this.id, content: e.target.innerHTML })
      }, 10000)
    },
    onDragStart (e) {
      this.$emit('on-drag-start', {
        id: this.id,
        x: e.clientX,
        y: e.clientY,
      })
    },
    onResizeStart (e) {
      this.$emit('on-resize-start', {
        id: this.id,
        x: e.clientX,
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.blackboard-item {
  position: absolute;
  & * {
    outline: none;
    &::selection {
      background-color: #777;
      color: #fff;
    }
  }
  .drag {
    height: 20px;
    &:hover {
      cursor: move;
      &::after {
        content: "";
        width: 100%;
        height: 5px;
        position: absolute;
        top: 5px;
        background: #777;
      }
    }
  }
  .size {
    position: absolute;
    right: -20px;
    width: 20px;
    height: 100%;
    &:hover {
      cursor: w-resize;
      &::after {
        content: "";
        height: calc(100% - 20px);
        width: 5px;
        position: absolute;
        right: 7px;
        top: 0;
        background: #777;
      }
    }
  }
}
</style>
